

var earthRadius=6378137; //地球半径
//经纬度坐标转墨卡托坐标
function lonlatToMeters([lon, lat]) {
  var mbyd = Math.PI * earthRadius / 180.0; //一度代表多少米
  var mx = lon * mbyd;
  var my = (Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180.0));
  my = my * mbyd;
  return [mx, my];
}
//墨卡托坐标转经纬度
function MetersToLonlat([x, y]) {
  var mbyd = Math.PI * earthRadius / 180; //一度代表多少米
  var lon = x / mbyd;
  var lat = y / mbyd;
  lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180.0)) - Math.PI / 2);
  return [lon, lat];
}




/**
 * 像素与经纬度/米的换算
 */
function GetPixelToLonLat(origin, x, y, resolution) {
  var lon = parseFloat(origin[0]) + x * resolution;
  var lat = parseFloat(origin[1]) - y * resolution;
  return [lon, lat];
}
function GetLonLatToPixel(origin, lon, lat, resolution) {
  var x = (lon-origin[0]) /resolution;
  var y = Math.abs(lat-origin[1]) /resolution;
  return [lon, lat];
}











/**
 * 地理范围的计算
 */
function GetTileExtent(topLeftX, topLeftY, row, col, resolution) {
  var xmin = topLeftX + resolution * col * 256;
  var xmax = topLeftX + resolution * (col + 1) * 256;
  var ymin = topLeftY - resolution * (row + 1) * 256;
  var ymax = topLeftY - resolution * row * 256;
  return [xmin, ymin, xmax, ymax];
};

/**
 * 瓦片行列号的计算
 */

function GetTileRowCol(extent,origin,resolution) {
  var startRow = Math.floor(Math.abs((extent[3] - origin[1]) / 256 / resolution));
  var endRow = Math.floor(Math.abs((extent[1] - origin[1]) / 256 / resolution));
  var startCol = Math.floor((extent[0] - origin[0]) / 256 / resolution);
  var endCol = Math.floor((extent[2] - origin[0]) / 256 / resolution);
  return [startCol, endCol, startRow, endRow];
}
